﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using JX.Application;
using JX.Core.Entity;
using JX.Infrastructure.Common;
using JX.Infrastructure.Framework.Jwt;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace JXWebApi.Controllers
{
    [EnableCors("AnyPolicy")]//设置跨域处理的代理
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserTokenController : Controller
    {
        private IUsersServiceApp _UserService;
        public UserTokenController(IUsersServiceApp userService)
        {
			_UserService = userService;
        }

		/// <summary>
		/// 通过用户名和密码，得到JwtToken
		/// </summary>
		/// <param name="username"></param>
		/// <param name="password"></param>
		/// <returns></returns>
		[HttpPost]
		public IActionResult GetToken(string username, string password)
		{
			try
			{
				if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
				{
					return ReturnErrorMsg("用户名或密码不能为空");
				}
				var userStatus = _UserService.Login(username, password);
				if (userStatus != UserStatusEnum.None)
				{
					switch (userStatus)
					{
						case UserStatusEnum.NoExist:
							return ReturnErrorMsg("用户名或密码不对");
						case UserStatusEnum.Locked:
							return ReturnErrorMsg("用户被锁定");
						case UserStatusEnum.WaitValidateByEmail:
						case UserStatusEnum.WaitValidateByAdmin:
						case UserStatusEnum.WaitValidateByMobile:
							return ReturnErrorMsg(EnumHelper.GetDescription(userStatus));
					}
				}
				var userDTO = _UserService.GetByUserName(username);
				if (userDTO == null)
				{
					return ReturnErrorMsg("用户不存在");
				}
				var claims = new List<Claim>()
				{
					new Claim(ClaimTypes.Name,userDTO.UserName)
					,new Claim(ClaimTypes.Sid,userDTO.UserID.ToString())
					,new Claim(ClaimTypes.Email,userDTO.Email)
					,new Claim(ClaimTypes.MobilePhone,userDTO.Mobile)
					,new Claim(ClaimTypes.Gender,userDTO.Sex.ToString())
					,new Claim("TrueName",userDTO.TrueName)
					,new Claim("GroupID",userDTO.GroupID.ToString())
					,new Claim("CompanyID",userDTO.CompanyID.ToString())
					,new Claim("ClientID",userDTO.ClientID.ToString())
					,new Claim("UserType",userDTO.UserType.ToString())
					,new Claim("UserFace",userDTO.UserFace)
					,new Claim("Sign",userDTO.Sign)
					,new Claim(ClaimTypes.Role,"管理员")
				};

				var userClaimsIdentity = new ClaimsIdentity(claims, "UserJwtBearer");
				//init the identity instances 
				var userPrincipal = new ClaimsPrincipal(userClaimsIdentity);

				//signin 
				//await HttpContext.SignInAsync("UserJwtBearer", userPrincipal, new AuthenticationProperties
				//{
				//	ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
				//	IsPersistent = false,
				//	AllowRefresh = false
				//});


				
				JwtUserInfo jwtUserInfo = new JwtUserInfo();
				jwtUserInfo.Sid = (int)userDTO.UserID;
				jwtUserInfo.Name = userDTO.UserName;
				jwtUserInfo.Role = "管理员";
				var jwtResult = JwtHelper.GetJwtResult(jwtUserInfo, ConfigHelper.GetAppSettingSection<JwtConfig>());
				return Json(jwtResult);
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 通过RefreshToken，得到新的JwtToken
		/// </summary>
		/// <param name="token"></param>
		/// <param name="userID"></param>
		/// <returns></returns>
		[HttpPost]
		public IActionResult RefreshToken(string token, int userID)
		{
			try
			{
				if (string.IsNullOrEmpty(token) || userID <= 0)
				{
					return ReturnErrorMsg("token不存在或用户ID为0");
				}
				var jwtResult = JwtHelper.RefreshToken(token, userID, ConfigHelper.GetAppSettingSection<JwtConfig>());
				return Json(jwtResult);
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 验证TOKEN
		/// </summary>
		/// <param name="token"></param>
		/// <returns></returns>
		[HttpPost]
		public IActionResult ValidateToken(string token)
		{
			try
			{
				if (string.IsNullOrEmpty(token))
				{
					return ReturnErrorMsg("token不存在");
				}
				List<Claim> Clims = null;
				var jwtResult = JwtHelper.ValidateToken(token, ConfigHelper.GetAppSettingSection<JwtConfig>(),out Clims);
				if (jwtResult)
				{
					List<object> result = new List<object>();
					foreach(var item in Clims)
					{
						var climsInfo = new { type = item.Type, value = item.Value };
						result.Add(climsInfo);
					}
					return Json(result);
				}
				else
				{
					return ReturnErrorMsg("验证失败");
				}
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 得到当前登录会员信息
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		[Authorize(AuthenticationSchemes = "UserJwtBearer", Roles = "管理员")]
		public IActionResult GetUserInfo()
		{
			try
			{
				List<object> result = new List<object>();
				foreach (var item in User.Claims)
				{
					var climsInfo = new { type = item.Type, value = item.Value };
					result.Add(climsInfo);
				}
				return Json(new { Status = true, Msg = "", Data = JsonConvert.SerializeObject(result) });
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 返回认证失败消息
		/// </summary>
		/// <param name="errMsg"></param>
		/// <returns></returns>
		private IActionResult ReturnErrorMsg(string errMsg)
		{
			return Json(new { Status = false, Msg = errMsg });
		}
	}
}